#include <stdio.h>
#include "lru.h"

struct lru lru;

int calc_hash(int id)
{
	return id % HASH_TABLE_SIZE;
}

void lru_cache_init()
{
	int i = 0;

	for(i=0; i<HASH_TABLE_SIZE; i++)
	{
		INIT_LIST_HEAD(&lru.hash_table[i]);
	}
	INIT_LIST_HEAD(&lru.lru_list);
}

void lru_cache_add(struct user *obj)
{
	int ident;
	
	ident = calc_hash(obj->id);
	list_add_head(&obj->hash_list, &lru.hash_table[ident]);
	list_add_head(&obj->lru, &lru.lru_list);
	lru.size++;

	if (lru.size > MAX_CACHE_SIZE)
	{
		lru_cache_remove(obj);
	}
}

void lru_cache_remove(struct user *obj)
{
	list_del(&obj->lru);
	list_del(&obj->hash_list);
	lru.size--;
	free(obj);
}

struct user *lru_cache_find(int id)
{
	int ident;
	struct list_head *head;
	struct user *obj;
	struct list_head *pos;

	ident = calc_hash(id);
	head = &lru.hash_table[ident];
	list_for_each_entry(obj, head, hash_list)
	{
		if (obj->id == id)
		{
			list_move(&obj->lru, &lru.lru_list);	
			return obj;	
		}
	}
	
	return 0;	
}


